package fr.rhoc.android.webservices;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;

public final class WebServicesUtils {

	public static void callService(String serviceUrl,
			List<NameValuePair> postParams) throws IOException {
		getHttpResponse(serviceUrl, postParams);
	}

	public static String callServiceAndGetResponseAsString(String serviceUrl,
			List<NameValuePair> postParams) throws IOException {

		HttpResponse response = getHttpResponse(serviceUrl, postParams);

		HttpEntity entity = response.getEntity();

		InputStream is = entity.getContent();
		BufferedReader reader = new BufferedReader(new InputStreamReader(is,
				"ISO8859-1"), 8);
		StringBuilder sb = new StringBuilder();
		String line = null;
		while ((line = reader.readLine()) != null) {
			sb.append(line);
		}
		is.close();

		return sb.toString();

	}

	private static HttpResponse getHttpResponse(String url,
			List<NameValuePair> postParams) throws IOException {

		final String proxyHost = android.net.Proxy.getDefaultHost();
		final int proxyPort = android.net.Proxy.getDefaultPort();

		DefaultHttpClient client = new DefaultHttpClient();
		if (proxyHost != null && !"".equals(proxyHost.trim())) {
			client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
					new HttpHost(proxyHost, proxyPort));
		}

		HttpPost httppost = new HttpPost(url);
		if (postParams != null && !postParams.isEmpty()) {
			httppost.setEntity(new UrlEncodedFormEntity(postParams));
		}

		return client.execute(httppost);

	}

}
